import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 场地数据映射
const fieldMap = {
  1: "伯纳乌球场",
  2: "诺坎普球场", 
  3: "老特拉福德球场",
  4: "伊蒂哈德球场",
  5: "安菲尔德球场",
  6: "斯坦福桥球场",
  7: "酋长球场",
  8: "安联球场",
  9: "威斯特法伦球场",
  10: "都灵安联球场"
};

// 模拟比赛数据
const mockMatches = [
  {
    id: 1,
    team_id: 1,
    vs_team_id: 2,
    dateTime: "2024-01-15 15:00",
    field_id: 1,
    score: [2, 1],
    comment: "精彩的对攻战，主队最后时刻绝杀"
  },
  {
    id: 2,
    team_id: 3,
    vs_team_id: 4,
    dateTime: "2024-01-16 19:30",
    field_id: 2,
    score: [0, 3],
    comment: "客队完全压制，大胜而归"
  },
  {
    id: 3,
    team_id: 5,
    vs_team_id: 6,
    dateTime: "2024-01-17 20:00",
    field_id: 3,
    score: [1, 1],
    comment: "势均力敌的比赛，双方各得一分"
  },
  {
    id: 4,
    team_id: 7,
    vs_team_id: 8,
    dateTime: "2024-01-18 16:30",
    field_id: 4,
    score: [3, 0],
    comment: "主队火力全开，三球大胜"
  },
  {
    id: 5,
    team_id: 9,
    vs_team_id: 10,
    dateTime: "2024-01-19 18:00",
    field_id: 5,
    score: [2, 2],
    comment: "进球大战，双方握手言和"
  },
  {
    id: 6,
    team_id: 11,
    vs_team_id: 12,
    dateTime: "2024-01-20 15:30",
    field_id: 6,
    score: [1, 0],
    comment: "小胜一球，主队艰难取胜"
  },
  {
    id: 7,
    team_id: 13,
    vs_team_id: 14,
    dateTime: "2024-01-21 19:00",
    field_id: 7,
    score: [4, 1],
    comment: "主队大胜，展现强大实力"
  },
  {
    id: 8,
    team_id: 15,
    vs_team_id: 1,
    dateTime: "2024-01-22 17:30",
    field_id: 8,
    score: [0, 2],
    comment: "客队反客为主，带走三分"
  },
  {
    id: 9,
    team_id: 2,
    vs_team_id: 3,
    dateTime: "2024-01-23 20:30",
    field_id: 9,
    score: [1, 3],
    comment: "客队状态火热，轻松获胜"
  },
  {
    id: 10,
    team_id: 4,
    vs_team_id: 5,
    dateTime: "2024-01-24 16:00",
    field_id: 10,
    score: [2, 1],
    comment: "激烈对抗，主队险胜"
  },
  {
    id: 11,
    team_id: 6,
    vs_team_id: 7,
    dateTime: "2024-01-25 18:30",
    field_id: 1,
    score: [0, 0],
    comment: "防守大战，双方互交白卷"
  },
  {
    id: 12,
    team_id: 8,
    vs_team_id: 9,
    dateTime: "2024-01-26 19:45",
    field_id: 2,
    score: [3, 2],
    comment: "进球如麻，主队笑到最后"
  },
  {
    id: 13,
    team_id: 10,
    vs_team_id: 11,
    dateTime: "2024-01-27 15:15",
    field_id: 3,
    score: [1, 4],
    comment: "客队大爆发，狂进四球"
  },
  {
    id: 14,
    team_id: 12,
    vs_team_id: 13,
    dateTime: "2024-01-28 17:00",
    field_id: 4,
    score: [2, 2],
    comment: "精彩平局，双方都有机会"
  },
  {
    id: 15,
    team_id: 14,
    vs_team_id: 15,
    dateTime: "2024-01-29 20:15",
    field_id: 5,
    score: [1, 1],
    comment: "势均力敌，各取一分"
  }
];

// 模拟异步获取比赛列表
export const fetchMatches = createAsyncThunk(
  'matches/fetchMatches',
  async (_, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      return mockMatches;
    } catch (error) {
      return rejectWithValue('获取比赛列表失败');
    }
  }
);

// 模拟搜索比赛
export const searchMatches = createAsyncThunk(
  'matches/searchMatches',
  async ({ searchTerm, teams }, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const filteredMatches = mockMatches.filter(match => {
        const homeTeam = teams.find(team => team.id === match.team_id);
        const awayTeam = teams.find(team => team.id === match.vs_team_id);
        const fieldName = fieldMap[match.field_id];
        
        const searchLower = searchTerm.toLowerCase();
        return (
          (homeTeam && homeTeam.name.toLowerCase().includes(searchLower)) ||
          (awayTeam && awayTeam.name.toLowerCase().includes(searchLower)) ||
          (fieldName && fieldName.toLowerCase().includes(searchLower)) ||
          match.comment.toLowerCase().includes(searchLower)
        );
      });
      
      return filteredMatches;
    } catch (error) {
      return rejectWithValue('搜索比赛失败');
    }
  }
);

// 模拟筛选比赛
export const filterMatches = createAsyncThunk(
  'matches/filterMatches',
  async ({ filterType, value }, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      let filteredMatches = [...mockMatches];
      
      if (filterType === 'date') {
        // 按日期筛选
        filteredMatches = mockMatches.filter(match => {
          const matchDate = new Date(match.dateTime);
          const filterDate = new Date(value);
          return matchDate.toDateString() === filterDate.toDateString();
        });
      } else if (filterType === 'result') {
        // 按比分状态筛选
        filteredMatches = mockMatches.filter(match => {
          const [homeScore, awayScore] = match.score;
          if (value === 'win') return homeScore > awayScore;
          if (value === 'lose') return homeScore < awayScore;
          if (value === 'draw') return homeScore === awayScore;
          return true;
        });
      }
      
      return filteredMatches;
    } catch (error) {
      return rejectWithValue('筛选比赛失败');
    }
  }
);

const matchSlice = createSlice({
  name: 'matches',
  initialState: {
    matches: [],
    filteredMatches: [],
    searchTerm: '',
    filterType: '',
    filterValue: '',
    loading: false,
    error: null,
    hasMore: true,
    currentPage: 1,
    pageSize: 10,
  },
  reducers: {
    setSearchTerm: (state, action) => {
      state.searchTerm = action.payload;
    },
    setFilter: (state, action) => {
      state.filterType = action.payload.type;
      state.filterValue = action.payload.value;
    },
    clearSearch: (state) => {
      state.searchTerm = '';
      state.filteredMatches = state.matches;
    },
    clearFilter: (state) => {
      state.filterType = '';
      state.filterValue = '';
      state.filteredMatches = state.matches;
    },
    resetMatches: (state) => {
      state.matches = [];
      state.filteredMatches = [];
      state.searchTerm = '';
      state.filterType = '';
      state.filterValue = '';
      state.currentPage = 1;
      state.hasMore = true;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取比赛列表
      .addCase(fetchMatches.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMatches.fulfilled, (state, action) => {
        state.loading = false;
        state.matches = action.payload;
        state.filteredMatches = action.payload;
        state.error = null;
      })
      .addCase(fetchMatches.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 搜索比赛
      .addCase(searchMatches.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchMatches.fulfilled, (state, action) => {
        state.loading = false;
        state.filteredMatches = action.payload;
        state.error = null;
      })
      .addCase(searchMatches.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 筛选比赛
      .addCase(filterMatches.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(filterMatches.fulfilled, (state, action) => {
        state.loading = false;
        state.filteredMatches = action.payload;
        state.error = null;
      })
      .addCase(filterMatches.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  },
});

export const { 
  setSearchTerm, 
  setFilter, 
  clearSearch, 
  clearFilter, 
  resetMatches 
} = matchSlice.actions;

// 导出场地映射
export { fieldMap };

export default matchSlice.reducer;
